package com.pdg.dungeondelver.configuration;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import org.newdawn.slick.SlickException;
import org.newdawn.slick.util.ResourceLoader;
import org.newdawn.slick.util.xml.XMLElement;
import org.newdawn.slick.util.xml.XMLElementList;
import org.newdawn.slick.util.xml.XMLParser;

public class Descriptor {
	private static final String TAG_TYPE = "type";
	private static final String TAG_TEMPLATE = "template";
	private Map<String,Object> properties;
	public Map<String,Object> getProperties(){
		return properties;
	}
	
	@SuppressWarnings("unchecked")
	public <T extends Object>T get(String name){
		return (T)properties.get(name);
	}
	
	public <T extends Object>void put(String name,T value){
		properties.put(name, value);
	}
	
	public Descriptor(XMLElement element,Configuration configuration){
		properties = loadPropertiesFromElement(element,configuration);
	}
	public Descriptor() {
		properties = new HashMap<String,Object>();
	}

	private Map<String,Object> loadPropertiesFromElement(XMLElement element, Configuration configuration){
		PropertySerializers generators = configuration.getPropertySerializers();
		Map<String,Object> result=new HashMap<String,Object>();
		String template = element.getAttribute(TAG_TEMPLATE);
		if(!template.isEmpty()){
			String[] templates = template.split(",");
			for(Integer index=0;index<templates.length;++index){
				XMLParser parser = new XMLParser();
				try {
					InputStream stream = ResourceLoader.getResourceAsStream(templates[index]);
					XMLElement root = parser.parse(templates[index],stream);
					Map<String,Object> templateProperties = loadPropertiesFromElement(root,configuration);
					result.putAll(templateProperties);
				} catch (SlickException e) {
					e.printStackTrace();
				}
			}
		}
		XMLElementList children = element.getChildren();
		for(Integer index=0;index<children.size();++index){
			XMLElement child = children.get(index);
			String name = child.getName();
			String type = child.getAttribute(TAG_TYPE);
			if(type.isEmpty()){
				type = generators.getDefault();
			}
			result.put(name, generators.get(type).deserialize(child, configuration));
		}
		return result;
	}
}
